package com.shen.system.service.impl;

import com.shen.system.entity.UserEntity;
import com.shen.system.info.RoleInfo;
import com.shen.system.info.UserInfo;
import com.shen.system.repostitory.RoleRepository;
import com.shen.system.repostitory.UserRepository;
import com.shen.system.service.UserService;
import com.shen.api.commons.SystemUtils;
import com.shen.system.util.ConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    final int ZERO = 0;

    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;

    @Override
    public boolean addUser(UserEntity userEntity) {
        UserInfo save = null;
        logger.info("system user service addUser start : "+ userEntity);
        logger.info("system user service addUser userRespository save start");
        try {
            UserInfo userInfo = ConvertUtil.userEntityConvertUserInfo(userEntity);
            //设定角色信息
            if (!SystemUtils.isNullOr(userEntity.getRolesStr())){
                String[] split = userEntity.getRolesStr().split(",");
                List<RoleInfo> roleInfos = new ArrayList<>();
                for (String ids : split){
                    //遍历角色的id
                     if (null != roleRepository.findById(Long.parseLong(ids)).get()){
                         roleInfos.add(roleRepository.findById(Long.parseLong(ids)).get());
                     }

                }
                //设置关机：  添加这个用户，它有哪些角色， 把数据保存在第三方表
                userInfo.setRoles(roleInfos);
            }
            save = userRepository.save(userInfo);
            logger.info("system user service addUser userRepository save end");
            logger.info("user:"+ save);
        }catch (Exception exception){
            logger.error("system user service addUser fail");
            return false;
        }
        if (!SystemUtils.isNull(save) && save.getUid()!=ZERO){
            return true;
        }
        return false;
    }


    @Override
    public boolean delUser(String uid) {
        //删除一条删除多条的业务逻辑
        String[] ids = uid.split("");
        if (SystemUtils.isNull(uid) || ids.length == 0){
            return false;
        }
        //删除一条数据 或  多条数据
        if (ids.length == 1){

            //先查询 后修改
            try {
                Long id = Long.parseLong(ids[0]);
                UserInfo userInfo = userRepository.findById(id).get();
                userInfo.setUstatus(1);
                userRepository.save(userInfo);
                return true;
            }catch (Exception exception){
                return false;
            }
        }else {
            //删除多挑
            try {
                HashSet<Long> sets = new HashSet<>();
                for (String id : ids) {
                    sets.add(Long.parseLong(id));
                }
                userRepository.updates(sets);
                return true;
            }catch (Exception exception){

                return false;
            }
        }
    }

    /**
     * 修改信息
     * @param userEntity
     * @return
     */
    @Override
    public boolean updUser(UserEntity userEntity) {
        //查询uid是否存在
        UserInfo userInfo = userRepository.findById(userEntity.getUid()).get();
        //2、根据前端的数据进行修改
        //代表这个信息不是空的 不需要修改
        //修改名字
        if (!SystemUtils.isNullOr(userEntity.getUname())){
            userInfo.setUname(userEntity.getUname());
        }
        //修改手机号
        if (!SystemUtils.isNullOr(userEntity.getUphone())){
            userInfo.setUphone(userEntity.getUphone());
        }

        UserInfo save = userRepository.save(userInfo);

        return true;
    }

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<UserEntity> findAllUser() {
        List<UserInfo> all = userRepository.findAll();

        return ConvertUtil.userInfosConvertUserEntitys(all);
    }

    @Override
    public List<UserEntity> findaddAllUserByWhere(UserEntity userEntity){

        //将前端来的实体类转换成数据可用的实体类
        UserInfo userInfo =  ConvertUtil.userEntityConvertUserInfo(userEntity);
        ExampleMatcher exampleMatcher= ExampleMatcher.matching()
                .withMatcher("uphone",m->m.contains())
                .withIgnorePaths("uid")
                .withIgnorePaths("ustatus");

        //根据实体类去构建查询条件
        Example example = Example.of(userInfo,exampleMatcher);
        //根据判断条件去查询数据

        List<UserInfo> all = userRepository.findAll(example);

        return ConvertUtil.userInfosConvertUserEntitys(all);
    }

    /**
     * 根据时间查询
     * @param t1 开始时间
     * @param t2 结束时间
     * @return
     */

    @Override
    public List<UserEntity> findAllByUtimeBetween(String t1, String t2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<UserInfo> userss = null;
        try {
            userss = userRepository.findAllByUtimeBetween(sdf.parse(t1), sdf .parse(t2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ConvertUtil.userInfosConvertUserEntitys(userss);

    }

    @Override
    public Map<String, Object> queryUsers(UserEntity userEntity) {
        Pageable pageable = null;
        if (!SystemUtils.isNullOr(userEntity.getSort())){
            String [] sorts = null;
            sorts = userEntity.getSort().split(",");
            if ("ASC".equals(userEntity.getSort())){
                pageable = PageRequest.of(userEntity.getCurrentPage(),userEntity.getPageSize(),Sort.Direction.ASC,sorts);
            }else {
                pageable = PageRequest.of(userEntity.getCurrentPage(),userEntity.getPageSize(),Sort.Direction.DESC,sorts);
            }
        }
        //查询条件
        Specification<UserInfo> spec = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                //自定义条件的对象
                Predicate predicate = cb.conjunction();

                //根据邮箱查询
                if (SystemUtils.isNullOr(userEntity.getUmail())){
                    predicate.getExpressions().add(cb.equal(root.get("umail"),userEntity.getUmail()));
                }
                //根据手机号是否模糊匹配查询
                if (SystemUtils.isNullOr(userEntity.getUphone())){
                    predicate.getExpressions().add(cb.like(root.get("uphone").as(String.class),"%"+userEntity.getUpass()+"%"));
                }

                //起始时间
                if (SystemUtils.isNullOr(userEntity.getStartTime())){
                    predicate.getExpressions().add(
                            cb.greaterThanOrEqualTo(root.get("utime").as(String.class),userEntity.getStartTime())
                    );
                }

                //结束时间
                if (SystemUtils.isNullOr(userEntity.getStartTime())){
                    predicate.getExpressions().add(
                            cb.lessThanOrEqualTo(root.get("utime").as(String.class),userEntity.getEndTime())
                    );
                }
                return predicate;
            }
        };
        Page<UserInfo> page = userRepository.findAll(spec,pageable);

        List<UserInfo> content = page.getContent();

        List<UserEntity> userEntities = ConvertUtil.userInfosConvertUserEntitys(content);

        Map<String,Object> map = new HashMap<>();
        map.put("users",userEntities);  //列表
        map.put("totalPage",page.getTotalPages()); //总页数
        map.put("currentPage",userEntity.getCurrentPage());
        map.put("pageSize",userEntity.getPageSize());
        return map;
    }



}
